<?php

namespace app\common\lib;

use think\facade\Log;

class Tool
{

    public static function wakeupOnLan($mac, $broadcast, $device=[]): ?string
    {
//        $loop = \React\EventLoop\Factory::create();
//        $wolFactory = new \Clue\React\Wol\Factory($loop);
//
//        $wolFactory->createSender($broadcast)->then(function(\Clue\React\Wol\Sender $wol)use($mac) {
//            $wol->send($mac);
//        });
//
//        $loop->run();
//        return '执行成功';

//        return exec("wakeonlan -i {$broadcast} -p 9 {$mac}");
        $networkInterface = config('app.interface');
	$wakeCommand = env('app.wake_command', 'etherwake');
        $command = "{$wakeCommand} -i \"{$networkInterface}\" -b \"{$mac}\"";
        Log::info("exec:$command");
	$output = exec($command);
        return $output;
    }

    public static function wakeOnLan($ip, $mac, $port=9): bool
    {
        $packet = str_repeat(chr(0xFF), 6);
        for($i = 0; $i < 6; $i++) $packet .= chr((int)substr($mac, $i, $i + 2));
        $nic = fsockopen("udp://" . $ip, $port);
        if(!$nic){
            fclose($nic);
            return false;
        }
        fwrite($nic, $packet);
        fclose($nic);
        return true;
    }

    public static function shutdownOnLan(string $ip, int $port): bool
    {
        try {
            /** @noinspection HttpUrlsUsage */
            $url = "http://{$ip}:{$port}";
//            $res = http_post($url, ["act" => "shutdown"]);
            $command = "curl --max-time 3 --location \"{$url}\" --header 'Content-Type: application/x-www-form-urlencoded' --data-urlencode act=shutdown";
            $res = exec($command);
//            $res = socket_post($ip, $port, ["act" => "shutdown"]);
            if (!empty($res) && isJson($res)) {
                $data = json_decode($res, true);
                if (!empty($data['status']) && $data['status'] == 1) {
                    return true;
                }
            }
        } catch (\Exception $e) {
            return false;
        }
        return false;
    }
}
